#!/usr/bin/python


"""
Module to display image using nxv
Images are temporaly stored in files

"""


import sys, os, threading
from tempfile import mktemp
from fulguro import flgrcore


#-------------------------------------------
# Procedures
#-------------------------------------------

def search_path():
    if sys.platform == 'win32':
        import _winreg
        nxvkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\NxV")
        nxv_path = _winreg.QueryValueEx(nxvkey,'Install_Dir')[0]
        _winreg.CloseKey(nxvkey)
        return nxv_path

    else:
        dir_to_check = ['/usr/bin','/usr/local/bin']
        for dir in dir_to_check:
            for lfile in (os.listdir(dir)):
                if lfile == 'nxv':
                    return dir
        return ''



def flgr_display(*args):

    nxv_path = search_path()

    if nxv_path == '':
        print "Could not find NxV !!\n"
        sys.exit()

    limage = []
    lfile = []

    for item in args:
        if str(type(item))=="<type 'str'>":
            lfile.append(item.replace(' ','_'))
        else:
            limage.append(item)	
                
    while len(limage)>len(lfile):
        lfile.append(mktemp())		

    for i in range(len(limage)):
        lfile[i]=lfile[i]+'.png'

    for i in range(len(limage)):
        if os.path.isfile(lfile[i]):
            newdisplay=False
        else:
            newdisplay=True
            break

    for i in range(len(limage)):
        flgrcore.flgr2d_save_png(limage[i],lfile[i])


    if newdisplay==True:
        os.spawnv(os.P_NOWAIT, nxv_path+'/nxv',['nxv','-RM']+lfile)

        



